import Router from '@koa/router';
import db from '../mysqlHelper.js';
import logger from '../logger.js';
import response from '../response.js';
import moment from 'moment';
import md5 from 'md5';

const router = new Router();
router.prefix('/api');

router.post('/:table/insert', async (ctx) => {
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }

    switch (ctx.params.table) {

        default:
            break;
    }
    let res = await db.create(ctx.params.table, body);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} create error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} create error :` + res.message);
        return;
    }
    if (ctx.params.table == 'order_info') {
        ctx.body = response.success({ id: body.id });
    } else {
        ctx.body = response.success({ id: res.insertId });
    }
});
function getConditions(tbaleName, body) {
    let conditions = {};
    //根据不同的表获取表的主键用于后续的更新和删除
    switch (tbaleName) {
        //case 'oper':
        //     if (body.account == null) {
        //         return { code: 0, conditions, msg: '缺少必填字段 account' };
        //     }
        //     conditions = { account: body.account };
        //     return { code: 1, conditions: conditions };
        // case "isp_info":
        //     if(body.isp_code == null){
        //         return { code: 0, conditions, msg: '缺少必填字段 isp_code' };
        //     }
        //     conditions = { isp_code: body.isp_code };
        //     return { code: 1, conditions: conditions };
        // case 'user_info':
        //     if (body.openid == null) {
        //         return { code: 0, conditions, msg: '缺少必填字段 openid' };
        //     }
        //     conditions = { openid: body.openid };
        //     return { code: 1, conditions: conditions };
        // case 'order_info':
        //     if(body.order_id == null){
        //         return { code: 0, conditions, msg: '缺少必填字段 order_id' };
        //     }
        //     conditions = { order_id: body.order_id };
        //     return { code: 1, conditions: conditions };
        default:
            if (body.id == null) {
                return { code: 0, conditions, msg: '缺少必填字段 id' };
            }
            conditions = { id: body.id };
            return { code: 1, conditions: conditions };
    }
}

router.post('/:table/update', async (ctx) => {
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions;
    let obj = await db.findOne(ctx.params.table, conditions);
    if (obj == null) {
        ctx.body = response.fail('要修改数据不存在');
        return;
    }
    // for (let key in body) {
    //     if (body[key] != undefined && body[key] != null) {
    //         obj[key] = body[key];
    //     }
    // }
    delete body.conditions;

    res = await db.update(ctx.params.table, body, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} update error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} update error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/:table/remove', async (ctx) => {
    let body = ctx.request.body;
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions;
    res = await db.deleteRow(ctx.params.table, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} delete error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} delete error :` + res.message);
        return;
    }
    if (ctx.params.table == 'device') {
        memDB.deleteDevice({ sn: body.sn });
    }
    ctx.body = response.success();
});
router.post('/:table/getList', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        body = { limit: 10, offset: 0, direction: 'desc' };
    } else {
        if (!body.direction) body.direction = 'desc';
    }
    if (ctx.params.table == 'oper') {
        ctx.body = response.fail('无权访问');
        return;
    }
    let res = await db.findAll(ctx.params.table, body.conditions, body.orderBy, body.direction, body.limit, body.offset, body.areaArr, body.likeArr, body.leftJoinArr, body.inArr, body.dispColumn, body.customizeWhere);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} getList error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} getList error :` + res.message);
        return;
    }
    if (res.count) {
        ctx.body = response.success({ rows: res.rows, count: res.count });
        return;
    } else {
        ctx.body = response.success(res);
    }
});


router.post('/realData/report', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let sqls = [];
    for (let i = 0; i < body.length; i++) {
        const element = body[i];

        if (typeof element.value.value == 'number') {
            sqls.push({ sql: 'update register set `last_value` = ? ,last_updateTime=? where id = ?', param: [element.value.value, moment().format('YYYY-MM-DD HH:mm:ss'), element.value.id] });
        } else if (typeof element.value.id == 'string') {
            sqls.push({ sql: 'update register set str_value =?,last_updateTime=? where id =?', param: [element.value.value, moment().format('YYYY-MM-DD HH:mm:ss'), element.value.id] });
        } else if (typeof element.value.id =='boolean') {
            sqls.push({ sql: 'update register set`last_value` = ?,last_updateTime=? where id =?', param: [parseInt(element.value.value) , moment().format('YYYY-MM-DD HH:mm:ss'), element.value.id] });
        }
         else {
            console.warn('数据类型错误', typeof element.value, JSON.stringify(element.value));
        }

    }
    if (sqls.length > 0) {
        let res = await db.transaction(sqls);
        if (res instanceof Error) {
            logger.error(`report error :` + res.message);
            ctx.body = response.fail(`report error :` + res.message);
            return;
        }
        console.log('更新以下数据:' , JSON.stringify(sqls));
    }
    ctx.body = response.success();
});

router.post('/getregister', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    console.log(body);
    if (body.plc_id == null) {
        ctx.body = response.fail('缺少必填字段 plc_id');
        return;
    }
    let sql = `select * from register where plc_id = ${body.plc_id}`;
    let res = await db.query(sql);
    if (res instanceof Error) {
        logger.error(`getregister error :` + res.message);
        ctx.body = response.fail(`getregister error :` + res.message);
        return;
    }
    ctx.body = response.success(res);
});

router.post('/getPlcList', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    let sql = `select * from plc where enable = 1`;
    let res = await db.query(sql);
    if (res instanceof Error) {
        logger.error(`getPlcList error :` + res.message);
        ctx.body = response.fail(`getPlcList error :` + res.message);
        return;
    }
    ctx.body = response.success(res);
})


export { router };
